/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-03-13 10:50:39
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-04-23 17:43:19
 */
import { useEffect, useId, useState } from 'react'
import { View, StyleSheet, ScrollView, TouchableHighlight } from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons'
import appColor from '../../utils/appColor'
import Request from '../../utils/Request'
import { randomStr } from '../../utils/index'
import { useColorModeValue, Text, Input, useToast, Button } from 'native-base'

const randomId = (len) => {
  let str = randomStr(len)
  let t = ((new Date()).valueOf() + '').slice(7)
  return str + t
}


function AddSite({ navigation, route }) {




  const [siteData, setSiteData] = useState({
    siteName: '',
    cookie: '',
    sort: '1',
    sid: randomId(5),
    plates: [{
      pid: randomId(8),
      pname: '',
      purl: '',
      sort: '1',
    }]
  })

  const [isModify, setIsModify] = useState(false)

  useEffect(() => {
    if (route.params?.siteName) {
      navigation.setOptions({ title: '修改站点' })
      setIsModify(true)
      setSiteData(route.params)
    } else {
      // 新增站点

    }
  }, [])

  const Toast = useToast()
  const saveSite = async () => {
    const data = await Request.post('/site/add', siteData)
    console.log('data', data)
    // isModify ? console.log('保存成功') : console.log('添加成功')
    Toast.show({ title: data.message, duration: 3000, placement: 'top' })
    if (data.code == 400) {

    } else {
      setTimeout(() => {
        navigation.navigate('home1', { update: true })
      }, 800)
    }
  }
  const delSite = async () => {
    const data = await Request.get('/site/del', { sid: siteData.sid })
    Toast.show({ title: data.message, duration: 3000, placement: 'top' })
    if (data.code == 400) {

    } else {
      setTimeout(() => {
        navigation.navigate('home1', { update: true })
      }, 800)
    }
  }

  const addPlate = () => {
    setSiteData((v) => {
      const newSiteData = { ...v }
      const len = newSiteData.plates.length
      newSiteData.plates = [...newSiteData.plates, {
        pname: "",
        purl: "",
        sort: len + 1 + '',
        pid: randomId(8)
      }]
      return newSiteData
    })
  }

  const removePlate = (i) => {
    setSiteData((last) => {
      const newSiteData = { ...last }
      newSiteData.plates.splice(i, 1)
      newSiteData.plates.forEach((plate, i) => plate.sort = i + 1 + '')
      return newSiteData
    })
  }

  const onChangeVal = (type, prop, val, index) => {
    let newSiteData = { ...siteData }
    if (type === 'site') {
      newSiteData[prop] = val
    } else {
      newSiteData.plates[index][prop] = val
    }
    setSiteData(newSiteData)
  }

  const pageBg = useColorModeValue(appColor.lightbg, appColor.darkbg)
  const cardBg = useColorModeValue(appColor.light2, appColor.dark2)
  const cardSplitBg = useColorModeValue(appColor.light3, appColor.dark3)
  const inputStyle = { base: "80%", md: "25%" }

  return (
    <ScrollView style={[styles.page, { backgroundColor: pageBg }]}>
      <Text style={styles.moduleTitle}>基础信息</Text>
      <View style={[styles.card, { backgroundColor: cardBg }]}>
        <View style={styles.inputItem}>
          <Text style={styles.inputItemLabel}>名称</Text>
          <Input w={inputStyle} value={siteData.siteName} returnKeyType={'next'} placeholder="站点名称" onChangeText={(v) => onChangeVal('site', 'siteName', v)}></Input>
        </View>

        <View style={styles.inputItem}>
          <Text style={styles.inputItemLabel}>cookie</Text>
          <Input w={inputStyle} value={siteData.cookie} returnKeyType={'next'} placeholder="示例 aa=11;bb=22;cc=33" onChangeText={(v) => onChangeVal('site', 'cookie', v)}></Input>
        </View>

        <View style={styles.inputItem}>
          <Text style={styles.inputItemLabel}>排序</Text>
          <Input w={inputStyle} value={siteData.sort} keyboardType={'numeric'} returnKeyType={'next'} placeholder="数字" onChangeText={(v) => onChangeVal('site', 'sort', v)}></Input>
        </View>
      </View>

      <Text style={[styles.moduleTitle, { marginTop: 10, transform: [{ translateY: 15 }] }]}>板块信息</Text>
      <Ionicons style={styles.addPlateIcon} onPress={addPlate} name={'add-circle-outline'} size={22} color={"#1989fa"}></Ionicons>


      <View style={[styles.card, { backgroundColor: cardBg }]}>

        {siteData.plates.map((plate, i) => (
          <View style={styles.plateItem} key={plate.pid}>
            {i ?
              <Ionicons style={styles.removePlateIcon} onPress={() => removePlate(i)} name={'remove-circle-outline'} size={22} color={"#ee0a24"}></Ionicons>

              : null
            }
            <View style={styles.inputItem}>
              <Text style={styles.inputItemLabel}>板块名</Text>
              <Input w={inputStyle} value={plate.pname} returnKeyType={'next'} placeholder="电影" onChangeText={(v) => onChangeVal('plate', 'pname', v, i)}></Input>
            </View>

            <View style={styles.inputItem}>
              <Text style={styles.inputItemLabel}>链接</Text>
              <Input w={inputStyle} value={plate.purl} returnKeyType={'next'} placeholder="https://xxx" onChangeText={(v) => onChangeVal('plate', 'purl', v, i)}></Input>
            </View>

            <View style={styles.inputItem}>
              <Text style={styles.inputItemLabel}>排序</Text>
              <Input w={inputStyle} value={plate.sort} keyboardType={'numeric'} placeholder="数字" onChangeText={(v) => onChangeVal('plate', 'sort', v, i)}></Input>
            </View>

            {
              siteData.plates.length !== 1 ? <View style={[styles.plateItemSplitLine, { backgroundColor: cardSplitBg }]}></View> : null
            }
          </View>
        ))}

      </View>

      <Button onPress={saveSite}>保存</Button>

      {isModify ?
        <>
          <View style={{ height: 20 }}></View>
          <Button colorScheme="secondary" onPress={delSite}>删除</Button>
        </> : null}

      {/* 占位 */}
      <View style={{ height: 30 }}></View>

    </ScrollView>
  );
}

const styles = StyleSheet.create({
  page: {
    paddingHorizontal: 15,
    padding: 15,
    height: '100%'
  },
  moduleTitle: {
    marginBottom: 5,
  },
  card: {
    borderRadius: 10,
    padding: 10
  },
  inputItem: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  inputItemLabel: {
    width: 65,
    paddingHorizontal: 10,
    textAlign: 'right'
  },
  plateItem: {

  },
  addPlateIcon: {
    textAlign: 'right',
    transform: [{ translateX: -10 }, { translateY: -10 }]
  },
  removePlateIcon: {
    textAlign: 'right',
    transform: [{ translateX: -5 }]
  },
  plateItemSplitLine: {
    height: 1,
    marginVertical: 20,
  }
})

export default AddSite